/**
 * Copyright (c) 2011 Roundarch (www.roundarch.com)
 *
 * Author Joshua Jung
 *
 * ---
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package com.roundarch.flex.controls
{
    import com.roundarch.flex.controls.dateSliderClasses.DateSliderConst;
    import com.roundarch.flex.controls.graphControlClasses.GraphControlAxisOptions;
    import com.roundarch.flex.controls.graphControlClasses.GraphControlSelector;
    import com.roundarch.flex.controls.graphControlClasses.GraphControlTickRenderer;
    import com.roundarch.flex.controls.graphControlInterfaces.IGraphControlChild;
    import com.roundarch.flex.controls.graphControlInterfaces.IGraphControlSelector;
    import com.roundarch.flex.controls.intervals.Interval;

    import flash.events.Event;
    import flash.geom.Point;

    import mx.formatters.DateFormatter;

    //-----------------------------
    //  Events
    //-----------------------------
    [Event(name = "change")]
    /**
     * @author jjung
     */
    public class DateSliderBase extends GraphControlBase
    {
        //---------------------------------------------------------------------
        //
        //  Variables
        //
        //---------------------------------------------------------------------
        private var currentWidth : Number = NaN;

        /**
         * @private
         *
         * Flag to tell the dateSlider to update its graph options in commitProperties.
         */
        public var rebuildOptionsFlag : Boolean = true;

        //---------------------------------------------------------------------
        //
        //  Properties
        //
        //---------------------------------------------------------------------
        //-----------------------------
        // timePerPixel
        //-----------------------------
        /**
         * @private
         */
        protected var _timePerPixel : Number = NaN;

        [Bindable("timePerPixelChanged")]
        /**
         * When set the amount of time per pixel never changes, even if the width
         * of hte control changes.
         *
         * When set, maxDate is ignored.
         *
         * @default NaN
         */
        public function get timePerPixel() : Number
        {
            return _timePerPixel;
        }

        /**
         * @private
         */
        public function set timePerPixel(value : Number) : void
        {
            if (value == _timePerPixel)
            {
                return;
            }

            _timePerPixel = value;

            rebuildOptionsFlag = true;

            invalidateProperties();

            dispatchEvent(new Event("timePerPixelChanged"));
        }

        //-----------------------------
        // selectedDates
        //-----------------------------
        public function get selectedDates() : Array
        {
            if (!_selectedPoints)
            {
                return null;
            }
            var ret : Array = new Array();

            for (var i : int = 0; i < _selectedPoints.length; i++)
            {
                ret.push(new Date(_selectedPoints[i].x as Number));
            }

            return ret;
        }

        public function set selectedDates(value : Array) : void
        {
            if (value)
            {
                for (var i : int = 0; i < value.length; i++)
                {
                    if (value[i] is Date)
                    {
                        value[i] = new Point(value[i].time, 0);
                    }
                }
            }

            super.selectedPoints = value;
        }

        //-----------------------------
        // maxDate
        //-----------------------------
        /**
         * @private
         */
        protected var _requestedMaxDate : Date;

        [Bindable("maxDateChanged")]
        /**
         * The maximum date that can be displayed.
         */
        public function get maxDate() : Date
        {
            if (!horizontalAxisOptions || !horizontalAxisOptions.minMax)
            {
                return null;
            }

            return new Date(horizontalAxisOptions.minMax.end);
        }

        /**
         * @private
         */
        public function set maxDate(value : Date) : void
        {
            if (value && maxDate && (value.time == maxDate.time))
            {
                return;
            }

            _requestedMaxDate = value;

            rebuildOptionsFlag = true;

            invalidateProperties();

            dispatchEvent(new Event("maxDateChanged"));
        }

        //-----------------------------
        // minDate
        //-----------------------------
        /**
         * @private
         */
        protected var _requestedMinDate : Date = null;

        [Bindable("minDateChanged")]
        /**
         * The minimum date that can be displayed.
         */
        public function get minDate() : Date
        {
            if (!horizontalAxisOptions || !horizontalAxisOptions.minMax)
            {
                return null;
            }

            return new Date(horizontalAxisOptions.minMax.start);
        }

        /**
         * @private
         */
        public function set minDate(value : Date) : void
        {
            if (value && minDate && (value.time == minDate.time))
            {
                return;
            }

            _requestedMinDate = value;

            rebuildOptionsFlag = true;

            invalidateProperties();

            dispatchEvent(new Event("minDateChanged"));
        }

        //-----------------------------
        // visibleMaxDate
        //-----------------------------
        /**
         * @private
         */
        protected var _requestedVisibleMaxDate : Date = new Date();

        [Bindable("visibleMaxDateChanged")]
        /**
         * The maximum date that can be displayed.
         */
        public function get visibleMaxDate() : Date
        {
            if (!horizontalAxisOptions || !horizontalAxisOptions.visibleMinMax)
            {
                return null;
            }

            return new Date(horizontalAxisOptions.visibleMinMax.end);
        }

        /**
         * @private
         */
        public function set visibleMaxDate(value : Date) : void
        {
            if (value && visibleMaxDate && (value.time == visibleMaxDate.time))
            {
                return;
            }

            _requestedVisibleMaxDate = value;

            rebuildOptionsFlag = true;

            invalidateProperties();

            dispatchEvent(new Event("visibleMaxDateChanged"));
        }

        //-----------------------------
        // visibleMinDate
        //-----------------------------
        /**
         * @private
         */
        protected var _requestedVisibleMinDate : Date = new Date();

        [Bindable("visibleMinDateChanged")]
        /**
         * The minimum date that can be displayed.
         */
        public function get visibleMinDate() : Date
        {
            if (!horizontalAxisOptions || !horizontalAxisOptions.visibleMinMax)
            {
                return null;
            }

            return new Date(horizontalAxisOptions.visibleMinMax.start);
        }

        /**
         * @private
         */
        public function set visibleMinDate(value : Date) : void
        {
            if (value && visibleMinDate && (value.time == visibleMinDate.time))
            {
                return;
            }

            _requestedVisibleMinDate = value;

            rebuildOptionsFlag = true;

            invalidateProperties();

            dispatchEvent(new Event("visibleMinDateChanged"));
        }

        //---------------------------------------------------------------------
        //
        //  Constructor
        //
        //---------------------------------------------------------------------
        /**
         *  Constructor
         */
        public function DateSliderBase()
        {
            super();

            addEventListener("widthChanged", widthChangedHandler);

            rebuildGraphOptions();

            // Set minimum date to 1 year before now
            minDate = new Date(2000, 0, 1);

            // Set maximum date to 1 year after now
            maxDate = new Date(2020, 0, 1);

            minHeight = 10;
        }

        //---------------------------------------------------------------------
        //
        //  Variables
        //
        //---------------------------------------------------------------------
        /**
         * Used by the axis renderer to come up with a label for a value.
         */
        public function axisLabelFunction(value : Number) : String
        {
            var dateFormatter : DateFormatter = new DateFormatter();
            dateFormatter.formatString = "DD/MM/YYYY HH:MM";

            return dateFormatter.format(new Date(value));
        }

        //---------------------------------------------------------------------
        //
        //  Methods
        //
        //---------------------------------------------------------------------
        [Bindable("selectedPointsChanged")]
        public function getDateFor(selector : IGraphControlSelector) : Date
        {
            return new Date(getSelectedPointFor(selector).x);
        }

        //---------------------------------------------------------------------
        //
        //  Overridden Methods
        //
        //---------------------------------------------------------------------
        /**
         * @inheritDoc
         */
        override protected function commitProperties() : void
        {
            if (rebuildOptionsFlag)
            {
                invalidateDisplayList();

                if (!isNaN(currentWidth))
                {
                    rebuildOptionsFlag = false;
                    rebuildGraphOptions();
                }
            }

            super.commitProperties();
        }

        /**
         * @inheritDoc
         */
        override protected function createChildren() : void
        {
            super.createChildren();

            for each (var child : * in getChildren())
            {
                if (child is IGraphControlChild)
                {
                    (child as IGraphControlChild).parentGC = this;
                }
            }
        }

        /**
         * Builds the options for this graphControl from scratch.
         */
        protected function rebuildGraphOptions() : void
        {
            var horizontalAxisOptions : GraphControlAxisOptions = new GraphControlAxisOptions();
            var verticalAxisOptions : GraphControlAxisOptions = new GraphControlAxisOptions();

            verticalAxisOptions.minMax = new Interval(0, 0);
            verticalAxisOptions.visibleMinMax = new Interval(0, height);

            if (_requestedMinDate && _requestedMaxDate)
            {
                horizontalAxisOptions.minMax = new Interval(_requestedMinDate.time, _requestedMaxDate.time);
            }
            if (_requestedVisibleMinDate && (_requestedVisibleMaxDate || !isNaN(timePerPixel)))
            {
                var endTime : Number = isNaN(timePerPixel) ? _requestedVisibleMaxDate.time : _requestedVisibleMinDate.time + (timePerPixel * currentWidth);

                horizontalAxisOptions.visibleMinMax = new Interval(_requestedVisibleMinDate.time, endTime);
            }

            horizontalAxisOptions.labelFunction = axisLabelFunction;

            this.horizontalAxisOptions = horizontalAxisOptions;
            this.verticalAxisOptions = verticalAxisOptions;

            invalidateAll();
            invalidateDisplayList();
        }

        /**
         * @inheritDoc
         */
        override protected function updateDisplayList(unscaledWidth : Number, unscaledHeight : Number) : void
        {
            super.updateDisplayList(unscaledWidth, unscaledHeight);

            // In order for timePerPixel to work we have to wait for our width to be passed to us.
            if (this.currentWidth != unscaledWidth)
            {
                this.currentWidth = unscaledWidth;

                invalidateProperties();
            }
        }

        protected function widthChangedHandler(event : Event) : void
        {
            rebuildOptionsFlag = true;

            invalidateProperties();
        }
    }
}
